package cc.itez.wx.linkman.mould;

import cc.itez.wx.linkman.val.MsgType;
import cc.itez.wx.linkman.val.Role;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.log4j.Log4j2;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.StringReader;
import java.util.List;

@Log4j2
@Data
@Accessors(chain = true)
@XmlRootElement(name = "xml")
@XmlAccessorType(XmlAccessType.FIELD)
public class WxMessage {
    /**
     * 角色
     */
    private List<Role> roles;

    /**
     * 接收用户（公众号微信ID）
     */
    @XmlElement(name = "ToUserName")
    private String toUserName;

    /**
     * 发送用户（公众号订阅者）
     */
    @XmlElement(name = "FromUserName")
    private String fromUserName;

    /**
     * 发送时间
     */
    @XmlElement(name = "CreateTime")
    private long createTime;

    /**
     * 消息类型
     */
    private MsgType msgType;

    @XmlElement(name = "MsgType")
    public void setMsgType(String type) {
        this.msgType = MsgType.of(type);
    }

    /**
     * 消息内容
     */
    @XmlElement(name = "Content")
    private String content;

    /**
     * 消息ID
     */
    @XmlElement(name = "MsgId")
    private String msgId;

    public static WxMessage load(String xml) {
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(WxMessage.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            StringReader reader = new StringReader(xml);
            return (WxMessage) jaxbUnmarshaller.unmarshal(reader);
        } catch (JAXBException e) {
            log.error(e);
            e.printStackTrace();
        }
        return null;
    }
}
